package com.ls.interceptor;

import com.alibaba.fastjson.JSON;
import com.ls.common.BaseContext;
import com.ls.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author atom.hu
 * @version V1.0
 * @Package com.ls.interceptor
 * @date 2021/10/13 16:37
 * 拦截后放行的逻辑判断
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //1.登陆了就放行，没有登陆就拦截，响应错误信息
        Object employee = request.getSession().getAttribute("employee");
        log.info("拦截到的路径：{}",request.getRequestURI());
//        2.判断是否为null，如果为null说明没有登陆，就行拦截处理。响应错误信息
        if (employee!=null){
            //已经登陆
            log.info("登陆");
            BaseContext.setCurrentId((long)employee);
            return true;
        }

//        if (employee != null || request.getSession().getAttribute("user") != null){
//            //已经登陆
//            log.info("登陆");
//            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));
//            BaseContext.setCurrentId((long)employee);
//            Long userId = (Long) request.getSession().getAttribute("user");
//            BaseContext.setCurrentId(userId);
//            return true;
//        }
        //这里改动也会造成添加失败

//        4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            return true;
        }

        log.info("还没有登录，阻止访问");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
